package com.example.zsydb.controller;

import com.example.zsydb.dto.GtlyQueryDTO;
import com.example.zsydb.entity.GtlyResult;
import com.example.zsydb.service.GtlyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Controller
public class GtlyController {

    private final GtlyService gtlyService;
    private final DateTimeFormatter inputFormatter = DateTimeFormatter.ISO_DATE; // yyyy-MM-dd
    private final DateTimeFormatter dbFormatter = DateTimeFormatter.ISO_DATE; // yyyy-MM-dd

    @Autowired
    public GtlyController(GtlyService gtlyService) {
        this.gtlyService = gtlyService;
    }

    // 创建作业区选项映射
    private Map<String, String> getKmOptions() {
        Map<String, String> kmOptions = new LinkedHashMap<>();
        kmOptions.put("", "-- 全部作业区 --");  // 空值表示查询全部
        for (int i = 1; i <= 9; i++) {
            kmOptions.put(String.valueOf(i), "第" + toChineseNumber(i) + "作业区");
        }
        return kmOptions;
    }

    // 将数字转换为中文数字
    private String toChineseNumber(int number) {
        String[] chineseNumbers = {"一", "二", "三", "四", "五", "六", "七", "八", "九"};
        return chineseNumbers[number - 1];
    }

    @GetMapping("/gtly")
    public String showForm(Model model) {
        model.addAttribute("query", new GtlyQueryDTO());
        model.addAttribute("kmOptions", getKmOptions());
        model.addAttribute("logoutUrl", "/logout");
        return "gtly-query";
    }

    // 添加数字转换工具方法供模板使用
    @ModelAttribute("numberUtils")
    public NumberUtils numberUtils() {
        return new NumberUtils();
    }

    public static class NumberUtils {
        public String toChinese(String number) {
            String[] chineseNumbers = {"一", "二", "三", "四", "五", "六", "七", "八", "九"};
            try {
                int num = Integer.parseInt(number);
                if (num >= 1 && num <= 9) {
                    return chineseNumbers[num - 1];
                }
            } catch (NumberFormatException e) {
                // 忽略转换错误
            }
            return number;
        }
    }

    @PostMapping("/gtly")
    public String queryResults(
            @ModelAttribute("query") GtlyQueryDTO queryDTO,
            Model model) {

        // 转换日期格式为字符串
        String csrqStr = null;
        if (queryDTO.getCsrq() != null && !queryDTO.getCsrq().isEmpty()) {
            try {
                LocalDate date = LocalDate.parse(queryDTO.getCsrq(), inputFormatter);
                csrqStr = date.format(dbFormatter);
            } catch (DateTimeParseException e) {
                // 处理日期格式错误
                model.addAttribute("dateError", "日期格式错误，请使用 YYYY-MM-DD 格式");
            }
        }

        // 使用第二个数据源执行查询
        List<GtlyResult> results = gtlyService.queryResults(
                queryDTO.getJh(),
                queryDTO.getKm(),
                csrqStr,
                queryDTO.getDm()
        );

        model.addAttribute("results", results);
        model.addAttribute("query", queryDTO);
        model.addAttribute("kmOptions", getKmOptions());
        model.addAttribute("logoutUrl", "/logout");
        // 添加分页信息（如果需要）
        model.addAttribute("hasResults", !results.isEmpty());
        return "gtly-query";
    }
}